import Request from '@/lib/luch-request/index.js';
import { baseUrl, getToken } from './app.js';
import { LoginCenterApi } from './modules/LoginCenterApi.js';

const getTokenStorage = () => {
  let token = '';
  try {
    token = uni.getStorageSync('token');
  } catch (e) {}
  return token;
};

const http = new Request();

/* 设置全局配置 */
http.setConfig((config) => {
  console.log(baseUrl, 'baseUrl');
  config.header = {
    ...config.header,
  };
  config.sslVerify = false;
  config.baseURL = baseUrl;
  // 自定义的配置
  config.custom = {
    auth: true, // 是否传token
  };
  return config;
});

http.interceptors.request.use(
  async (config) => {
    config.header = {
      ...config.header,
      token: getTokenStorage().token,
    };

    return config;
  },
  (config) => {
    return Promise.reject(config);
  }
);

http.interceptors.response.use(
  async (response) => {
    console.log(response, '【拦截响应】');
    // if (response.data.code == -1) {
    //   uni.clearStorageSync('token');
    //   // uni.clearStorageSync('userInfo');
    //   getToken().then(() => {});
    // }
	 if (response.data.code == -1) {
	      uni.clearStorageSync('token');
	      await getToken();
	      let result = http.request(response.config);
	      return result;
	    }
    return response;
  },
  async (response) => {
    console.log(response, 'response');
    /*  对响应错误做点什么 （statusCode !== 200）*/
    console.log('对响应错误做点什么', response);
    if ((response.data.code = -1)) {
      uni.clearStorageSync('token');
      // uni.reLaunch({
      // 	url: "/pages/tabbar/index/index",
      // });
      // uni.showToast({
      // 	title: '登录凭证过期,请重新登录',
      // 	icon: 'none'
      // })
      getToken().then(() => {});
    }
    if (response.statusCode == 500) {
      uni.showToast({
        icon: 'error',
        title: '服务器错误',
      });
    }
    return Promise.reject(response);
  }
);

export default http;
